package cn.promonkey.api.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.promonkey.core.dto.UserDto;
import cn.promonkey.core.response.ResultMsg;
import cn.promonkey.core.security.SecurityService;
import cn.promonkey.core.toolkit.QueryGenerator;
import cn.promonkey.core.toolkit.UserInfoUtils;
import cn.promonkey.api.contract.entity.Contract;
import cn.promonkey.api.contract.service.ContractService;
import cn.promonkey.api.group.entity.Group;
import cn.promonkey.api.group.service.GroupService;
import cn.promonkey.api.system.entity.System;
import cn.promonkey.api.system.service.SystemService;
import cn.promonkey.api.user.service.UserService;
import lombok.extern.slf4j.Slf4j;

import static org.mockito.ArgumentMatchers.anyCollection;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/** @author <no value> */
@Slf4j
@RestController
@RequestMapping("/system/")
public class SystemController {
  final SystemService systemService;
  final ContractService contractService;
  final GroupService groupService;
  
  public SystemController(SystemService systemService,ContractService contractService,GroupService groupService) {
    this.systemService = systemService;
    this.contractService = contractService;
    this.groupService = groupService;
  }

  @RequestMapping("getPage")
  public String getPage(
      System system,
      @RequestParam(name = "page", defaultValue = "1") Integer page,
      @RequestParam(name = "size", defaultValue = "10") Integer size,
      HttpServletRequest request) {
    QueryWrapper<System> queryWrapper = QueryGenerator.initQueryWrapper(system, request.getParameterMap());
    Page<System> pageable = new Page<>(page, size);
    IPage<System> pageList = systemService.page(pageable, queryWrapper);
    return ResultMsg.success(pageList);
  }

  @RequestMapping(value = "getAll")
  public String getAll() {
	  QueryWrapper<System> queryWrapper = new QueryWrapper<>();
	  UserDto sysUser = UserInfoUtils.getUserInfo();//SecurityService.getCurrentUserAndCheck(null);
      queryWrapper.eq("business_id", sysUser.getBusinessId());
    return ResultMsg.success(systemService.list(queryWrapper));
  }
  
  @RequestMapping(value = "save", method = RequestMethod.POST)
  public String save(@RequestBody System system) {
	  UserDto sysUser = UserInfoUtils.getUserInfo();//SecurityService.getCurrentUserAndCheck(null);
	  int[] statusList = {1,2,3};
	  //判断合同内容是否能够新建系统
	  QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
	  queryWrapper.eq("business_id", sysUser.getBusinessId()).le("start_time", new Date()).ge("end_time",new Date()).in("status", statusList);;
	  List<Contract> contactList = contractService.list(queryWrapper);
	  if(contactList==null || contactList.size()==0) {
		  return ResultMsg.fail("没找到对应的合同信息，请联系销售人员确认！");
	  }
	  int systemNum = contactList.stream().collect(Collectors.summingInt(Contract::getSystemNum));
	  QueryWrapper<System> systemWrapper = new QueryWrapper<>();
	  systemWrapper.eq("business_id", sysUser.getBusinessId()).eq("status", 1);
	  long useNum = systemService.count(systemWrapper);
	  if(useNum>=systemNum) {
		  return ResultMsg.fail("已达到合同中的系统限额，请联系销售人员确认！");
	  }
	  //设置企业id及创建者id
	  system.setBusinessId(sysUser.getBusinessId());
	  system.setCreateId(sysUser.getUserId());
	  systemService.save(system);
	  //生成默认权限组
	  Group group = new Group();
	  group.setBusinessId(sysUser.getBusinessId());
	  group.setSystemId(system.getSystemId());
	  group.setUserId(sysUser.getUserId());
	  group.setType(1);
	  group.setStatus(1);
	  group.setGroupName("默认权限组");
	  groupService.save(group);
	  
    return ResultMsg.success();
  }

  @RequestMapping(value = "edit", method = RequestMethod.POST)
  public String edit(@RequestBody System system) {
	  if(system.getStatus()!=null && system.getStatus()==1) {
		  UserDto sysUser = UserInfoUtils.getUserInfo();//SecurityService.getCurrentUserAndCheck(null);
		  int[] statusList = {1,2,3};
		  //判断合同内容是否能够新建系统
		  QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
		  queryWrapper.eq("business_id", sysUser.getBusinessId()).le("start_time", new Date()).ge("end_time",new Date()).in("status", statusList);
		  List<Contract> contactList = contractService.list(queryWrapper);
		  if(contactList==null || contactList.size()==0) {
			  return ResultMsg.fail("没找到对应的合同信息，请联系销售人员确认！");
		  }
		  int systemNum = contactList.stream().collect(Collectors.summingInt(Contract::getSystemNum));
		  QueryWrapper<System> systemWrapper = new QueryWrapper<>();
		  systemWrapper.eq("business_id", sysUser.getBusinessId()).eq("status", 1).ne("system_id", system.getSystemId());
		  long useNum = systemService.count(systemWrapper);
		  if(useNum>=systemNum) {
			  return ResultMsg.fail("已达到合同中的系统限额，请联系销售人员确认！");
		  }
	  }
    return ResultMsg.success(systemService.updateById(system));
  }

  @RequestMapping(value = "get")
  public String get(@RequestParam(name = "id") Long id) {
    return ResultMsg.success(systemService.getById(id));
  }

  @RequestMapping(value = "delete", method = RequestMethod.POST)
  public String delete(@RequestBody Long id) {
    return ResultMsg.success(systemService.removeById(id));
  }
}
